package com.tudouji.project.harvest.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.MD5Utils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.framework.config.DwlConfig;
import com.tudouji.framework.config.WeighConfig;
import com.tudouji.project.harvest.domain.RecordData;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.system.domain.SysConfig;
import com.tudouji.project.system.mapper.SysConfigMapper;
import com.tudouji.project.weigh.domain.WeightData;
import com.tudouji.project.weigh.service.IWeightDataService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.project.harvest.domain.Weighlist;
import com.tudouji.project.harvest.service.IWeighlistService;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.common.utils.poi.ExcelUtil;
import com.tudouji.framework.web.page.TableDataInfo;

/**
 * 过磅单Controller
 *
 * @author tudouji
 * @date 2021-05-12
 */
@RestController
@RequestMapping("/harvest/weighlist")
public class WeighlistController extends BaseController {
    @Autowired
    private IWeighlistService weighlistService;
    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private IWeightDataService weightDataService;

    public static HashMap<String, String> hashMap = new HashMap<>();

    /**
     * 查询过磅单列表
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:list')")
    @GetMapping("/list")
    public TableDataInfo list(Weighlist weighlist) {
        startPage();
        List<Weighlist> list = weighlistService.selectWeighlistList(weighlist);
        return getDataTable(list);
    }

    /**
     * 导出过磅单列表
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:export')")
    @Log(title = "过磅单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Weighlist weighlist) {
        List<Weighlist> list = weighlistService.selectWeighlistList(weighlist);
        ExcelUtil<Weighlist> util = new ExcelUtil<Weighlist>(Weighlist.class);
        return util.exportExcel(list, "weighlist");
    }

    /**
     * 获取过磅单详细信息
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid) {
        return AjaxResult.success(weighlistService.selectWeighlistById(guid));
    }

    /**
     * 新增过磅单
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:add')")
    @Log(title = "过磅单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Weighlist weighlist) {
        return toAjax(weighlistService.insertWeighlist(weighlist));
    }

    /**
     * 修改过磅单
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:edit')")
    @Log(title = "过磅单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Weighlist weighlist) {
        return toAjax(weighlistService.updateWeighlist(weighlist));
    }

    /**
     * 删除过磅单
     */
    @PreAuthorize("@ss.hasPermi('harvest:weighlist:remove')")
    @Log(title = "过磅单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids) {
        return toAjax(weighlistService.deleteWeighlistByIds(guids));
    }

    /**
     * 测试-获取配置
     */
    @PostMapping("/getConfig")
    public AjaxResult getConfig() {
        AjaxResult result = AjaxResult.success();
        SysConfig queryTime = new SysConfig();
        queryTime.setConfigKey("queryTime");
        queryTime = configMapper.selectConfig(queryTime);
        SysConfig period = new SysConfig();
        period.setConfigKey("period");
        period = configMapper.selectConfig(period);
        result.put("profile", WeighConfig.getProfile());
        result.put("queryTime", queryTime.getConfigValue());
        result.put("period", Integer.valueOf(period.getConfigValue()));

        logger.info("getConfig: " + DateUtils.getTime());
        logger.info("profile: " + WeighConfig.getProfile());
        logger.info("queryTime: " + queryTime.getConfigValue());
        logger.info("period: " + Integer.valueOf(period.getConfigValue()));
        return result;
    }

    /**
     * 测试-送过磅记录
     */
    @PostMapping("/loadWeight")
    public AjaxResult loadWeight(@RequestBody WeightData weightData) {
        logger.info(weightData.toString());
        AjaxResult result = AjaxResult.success();
        //loadWeightSwitch为0时，不处理接收到的数据
        SysConfig loadWeightSwitch = new SysConfig();
        loadWeightSwitch.setConfigKey("loadWeightSwitch");
        loadWeightSwitch = configMapper.selectConfig(loadWeightSwitch);
        if (StringUtils.equalsIgnoreCase("0", loadWeightSwitch.getConfigValue())){
            logger.info("loadWeightSwitch of sys_config is " + loadWeightSwitch + ", not deal with below!");
            return result;
        }

        SysConfig queryTime = new SysConfig();
        queryTime.setConfigKey("queryTime");
        queryTime = configMapper.selectConfig(queryTime);
        result.put("profile", WeighConfig.getProfile());
        result.put("queryTime", queryTime.getConfigValue());
        try {
            String code = weightData.getCode();
            String md5 = MD5Utils.encryString(weightData.getCode() + weightData.getCarCode() + weightData.getmWeight()
                    + weightData.getpWeight() + weightData.getWeight());
            if (StringUtils.isEmpty(hashMap.get(code))) {
                boolean isOk = setData(weightData, md5);
                result.put("isOk", isOk);
            } else {
                if (StringUtils.equalsIgnoreCase(hashMap.get(code), md5)) {
                    result.put("isOk", true);
                }else{
                    boolean isOk = setData(weightData, md5);
                    result.put("isOk", isOk);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("isOk", false);
            return result;
        }
        return result;
    }

    private boolean setData(WeightData weightData, String md5) {
        //md5值不相同，到数据库中查找更新
        boolean isOK = weightDataService.addOrupdateWeightData(weightData);
        if (isOK) {
            //更新map中的md5
            hashMap.put(weightData.getCode(), md5);
        }
        return isOK;
    }
}
